package com.github.wxiaoqi.security.common.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;


public class FilterUtil {

	/**
	 * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * @param params  需要排序并参与字符拼接的参数组
	 * @return 拼接后字符串
	 */
	@SuppressWarnings("unchecked")
	public static String createLinkString(Map<String, Object> params) {

		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);

		String prestr = "";

		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			Object obj = params.get(key);
			if (obj instanceof Map){
				prestr = prestr + key + "==" + createLinkString((Map<String, Object>) obj)
				+ "&&";
			}else {
					if(null!=obj){
						String value = obj.toString();
						if(!StringUtils.isEmpty(value)){
							if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
								prestr = prestr + key + "=" + value;
							} else {
								prestr = prestr + key + "=" + value + "&";
							}
						}
					}
			}
		}
		return prestr;
	}

	/**
	 * 除去签名参数
	 * @param sArray 签名参数组
	 * @return 去掉空值的新签名参数组
	 */
	public static Map<String, Object> paraFilter(Map<String, Object> sArray) {

		Map<String, Object> result = new HashMap<String, Object>();

		if (sArray == null || sArray.size() <= 0) {
			return result;
		}

		for (String key : sArray.keySet()) {
			String strValue = null;
			Object value = sArray.get(key);
			if (key.equalsIgnoreCase("sign_type")
					|| key.equalsIgnoreCase("sign")
					|| key.equalsIgnoreCase("$sessionClass")
					|| key.equalsIgnoreCase("TransCode")
					|| key.equalsIgnoreCase("serviceCode")) {
				continue;
			}
			if (value != null) {
				strValue = value.toString().trim();
			}
			if (value == null) {
				strValue = "";
			}

			result.put(key, strValue);
		}

		return result;
	}
	
	/**
	 * 转换参数值
	 * 
	 * */
    public static Map<String,Object>toMapStringParams(Map<String,String[]>params){
    	Map<String, Object>newParams=new HashMap<String,Object>();
    	if(params.size()>0){
    		for (Entry<String, String[]> entry : params.entrySet()) {
    			if(entry.getValue().length>0){
    				newParams.put(entry.getKey(), entry.getValue()[0]);
    			}else{
    				newParams.put(entry.getKey(), "");
    			}
    			
    		}
    	}
		return newParams;
    }
    
    /**
     * 
     * 
     * */
    public static void main(String[] args) {
    	Map<String, Object> sArray=new HashMap<String, Object>();
    	sArray.put("aas", 1122);
    	sArray.put("b", "");
    	sArray.put("c", "na");
    	sArray.put("d", "mi");
    	sArray.put("a", "cdscd");
    	sArray.put("mmmmm", null);
    	//System.out.println(createLinkString(sArray));
    	System.out.println(sArray.containsKey("mmmmm"));
	}

}


